<template>
	<view class="list-search-page">
		<z-paging ref="paging" v-model="merchantsList" :default-page-size="10" :show-scrollbar="false"
			:paging-style="{ minHeight: '100vh', backgroundColor: '#F5F6F7' }" :refresher-enabled="true"
			:loading-more-enabled="true" height="100vh" @query="queryList" @scroll="handlePageScroll">
			<template #top>
				<!-- <nav-bar ref="navBarRef" :title="title" :bgColor="navBgColor" fixed showHeaderIcon
					:allowMaskClose="false" :showCancle="showCancle" :isNeedAll="false" class="page-nav-bar"
					@locationChanged="locationChanged" /> -->
				<u-navbar
					:title="title"
					:autoBack="true"
					bgColor="transparent"
					:titleStyle="{color: '#000'}"
					left-icon-color="#606266"
				/>
				<u-swiper :list="bannerUrl" indicatorMode="dot" indicator height="450rpx" @click="jumpBanner" />
				<!-- 分类选项卡 - 按钮式样式 -->
				<view v-if="list1.length > 1" class="tabs-container">
					<scroll-view scroll-x class="tabs-scroll" show-scrollbar="false">
						<view class="button-tabs">
							<view v-for="(item, index) in list1" :key="index" class="tab-button"
								:class="{ 'tab-button-active': currentTab === index }" @click="click(item)">
								{{ item.name }}
							</view>
						</view>
					</scroll-view>
				</view>
				<!-- 搜索框：仅酒店和美食显示 -->
				<view v-if="[2, 3, 4, 5, 6].includes(merchantsType)" class="search-box">
					<view class="location" @click.stop="selectALocation">
						<uni-icons type="location" size="20" style="margin-right: 10rpx" />
						<view class="location-title">{{ selectedLocation.title }}</view>
						<view class="location-arrow"></view>
					</view>
					<view class="search">
						<input
							v-model="searchParams.ShopName"
							type="text"
							placeholder="请输入名称搜索"
							placeholder-style="color: #999"
							@confirm="onSearch"
							@keyup.enter.native="onSearch"
							/>
						<view class="search-btn">
							<uni-icons type="search" size="24" @click="onSearch"></uni-icons>
						</view>
					</view>
				</view>
				<!-- 当merchantsType为3和4时显示筛选器 -->
				<sl-filter v-if="[3, 4].includes(merchantsType)" :independence="true" :topFixed="false" :navHeight="44"
					:color="titleColor" :innerItemWidth="innerItemWidth" :isDesc="IsDesc" :themeColor="themeColor"
					:menuList.sync="filterList" :class="merchantsType === 3 ? 'flex-start' : ''"
					@result="handleResult" />

			</template>

			<!-- 商品列表 -->
			<view class="list-content">
				<view class="merchants-list" v-if="merchantsList && merchantsList.length > 0">
					<!-- 景区 -->
					<template v-if="merchantsType === 2">
						<scenic-item
							v-for="(item, index) in merchantsList"
							:key="index"
							:ref="`scenicRef_${item.Id}`"
							:data="item"
							:style="{ '--item-index': index }"
							@click="handleGoToDetail(item)"
							@handleCheck="handleCheckScenic"
						/>
					</template>
					<!-- 美食 -->
					<template v-else-if="merchantsType === 3">
						<gourmet-item v-for="(item, index) in merchantsList" :key="index" :data="item"
							:style="{ '--item-index': index }" @click="handleGoToDetail(item)" />
					</template>
					<!-- 酒店 -->
					<template v-else-if="merchantsType === 4">
						<hotel-item v-for="(item, index) in merchantsList" :key="index" :data="item"
							:style="{ '--item-index': index }" @click="handleGoToDetail(item)" />
					</template>
					<!-- 旅行社 -->
					<template v-else-if="merchantsType === 5">
						<study-item
							v-for="(item, index) in merchantsList"
							:key="index"
							:ref="`studyRef_${item.Id}`"
							:data="item"
							:style="{ '--item-index': index }"
							@click="handleGoToDetail(item)"
							@handleCheck="handleCheckStudy"
						/>
					</template>
					<!-- 研学 -->
					<template v-else-if="merchantsType === 6">
						<photography-item
							v-for="(item, index) in merchantsList"
							:key="index"
							:ref="`photographyRef_${item.Id}`"
							:data="item"
							:style="{ '--item-index': index }"
							@click="handleGoToDetail(item)"
							@handleCheck="handleCheckPhotography"
						/>
					</template>
				</view>

				<!-- 空状态 -->
				<empty v-else-if="merchantsList && merchantsList.length === 0" />
			</view>
		</z-paging>
	</view>
</template>

<script>
	import uniLoadMore from "@/components/uni-load-more/uni-load-more.vue";
	import empty from "@/components/empty.vue";
	import MerchantConfig from "./config.js";
	import Filter from "./filter.js";
	import slFilter from "@/mall_subpages/components/sl-filter/sl-filter.vue";
	import GourmetItem from "./item/gourmet.vue";
	import HotelItem from "./item/hotel.vue";
	import studyItem from "./item/study.vue";
	import scenicItem from "./item/scenic.vue";
	import photographyItem from "./item/photography.vue";
	import navBar from "@/components/layout/navbar/index.vue";
	import {
		getBusinessClassifyGroup,
		getShopBgList
	} from "@/api/mall.js";
	import uniFab from "@/components/uni-fab/uni-fab.vue";
	import {
		useArticleApi
	} from "@/api/homePage";
	import { mapState, mapMutations } from "vuex";

	export default {
		name: "MerchantsList",
		components: {
			studyItem,
			empty,
			uniLoadMore,
			uniFab,
			GourmetItem,
			HotelItem,
			scenicItem,
			photographyItem,
			slFilter,
			navBar,
		},
		data() {
			return {
				currentCheckId: undefined,
				navBgColor: "transparent",
				title: "",
				bannerUrl: [],
				bannerList: [],
				// u-tabs数据，将在onLoad中动态设置
				list1: [],
				currentTab: 0,
				// 商家类型
				merchantsType: 0,
				// 商家列表
				merchantsList: [],
				BusinessId: "",
				loadingType: "more",
				// 筛选相关数据
				filterList: [],
				themeColor: "#000000",
				titleColor: "#666666",
				IsDesc: {},
				searchParams: {
					// 产品名称
					ShopName: "",
					// FiledOrder: "Sort desc",
					FiledOrder: "IsBusiness asc,Sort desc",
					// FiledOrder: "PerConsumption asc",

				},
				contentTextObj: {
					contentdown: "加载更多",
					contentrefresh: "加载中",
					contentnomore: "没有更多了",
				},
			};
		},
		computed: {
			...mapState({
				locationList: state => state.base.locationList,
				selectedLocation: (state) => state.base.selectedLocation,
			}),
			innerItemWidth() {
				if (this.merchantsType === 4) return 'calc(100% / 3)';
				return 'calc(100% / 2)';
			},
			showCancle() {
				return this.selectedLocation.value !== 0;
			}
		},
		onLoad(options) {
			console.log(options);
			if(options && options.ShopName){
				this.searchParams.ShopName = options.ShopName
			}
			this.initPageData(options);
			// 根据商家类型设置tabs数据
			this.initTabsData();
			
			// if (this.selectedLocation.value === 0) {
			// 	this.$refs.navBarRef && this.$refs.navBarRef.showCustomAction();
			// }
		},
		mounted() {
			// 初始化国际化文本
			this.updateContentText();
		},
		methods: {
			...mapMutations(['setSelectedLocation']),
			selectALocation() {
				uni.showActionSheet({
					itemList: this.locationList.map(item => item.title),
					success: (res) => {
					const selectedLocation = this.locationList[res.tapIndex]
					this.setSelectedLocation(selectedLocation)
					this.$refs.paging.reload();
					}
				})
			},
			// 更新国际化文本
			updateContentText() {
				try {
					this.contentTextObj = {
						contentdown: this.$t("merchants.loadMore") || "加载更多",
						contentrefresh: this.$t("merchants.loading") || "加载中",
						contentnomore: this.$t("merchants.noMore") || "没有更多了",
					};
				} catch (error) {
					console.error("更新国际化文本失败:", error);
					this.contentTextObj = {
						contentdown: "加载更多",
						contentrefresh: "加载中",
						contentnomore: "没有更多了",
					};
				}
			},

			handlePageScroll(e) {
				const scrollTop = e.detail.scrollTop;
				if (scrollTop > 185) {
					this.navBgColor = "#fff";
				} else {
					this.navBgColor = "transparent";
				}
			},
			// 初始化tabs数据
			async initTabsData() {
				try {
					// 使用getBusinessClassifyGroup接口获取二级分类数据
					const {
						Data
					} = await getBusinessClassifyGroup({
						BusinessClassifyId: this.merchantsType,
					});

					if (Data && Array.isArray(Data)) {
						// 转换接口返回的数据为tab格式
						this.list1 = [{
								name: this.$t("merchants.all")
							},
							...Data.map((item) => ({
								name: item.ClassifyGroupName,
								id: item.Id,
							})),
						];
					} else {
						// 如果接口没有返回数据，使用默认配置
						this.list1 = MerchantConfig.tabs[this.merchantsType] || [];
					}
				} catch (error) {
					console.error("获取二级分类数据失败:", error);
					// 失败时使用默认配置
					this.list1 = MerchantConfig.tabs[this.merchantsType] || [];
				}
			},

			// tab点击事件
			click(item) {
				console.log("item", item);
				// 找到点击的索引
				this.currentTab = this.list1.findIndex((i) => i.name === item.name);
				// 根据选中的标签筛选数据
				this.filterByTab(item);
			},

			// 根据tab标签筛选数据
			filterByTab(item) {
				// 如果是"全部"标签，不设置分类ID
				if (item.name === this.$t("merchants.all")) {
					// 全部不需要筛选
					delete this.searchParams.ProductCategoryName;
					delete this.searchParams.BusinessClassifyGroupId;
				} else {
					// 删除ProductCategoryName参数，使用BusinessClassifyGroupId代替
					delete this.searchParams.ProductCategoryName;
					// 设置二级分类ID
					this.searchParams.BusinessClassifyGroupId = item.id;
				}

				// 重新加载数据
				this.$refs.paging.reload();
			},

			// 初始化页面数据
			initPageData(options) {
				const {
					type
				} = options || {};
				// 设置标题，添加默认值
				// this.title = MerchantConfig.merchants_enums[type] || "商家列表";
				this.title = ""
				// 设置页面参数
				this.merchantsType = parseInt(type) || 0;

				// 如果是住宿类型，初始化筛选数据
				if ([3, 4].includes(this.merchantsType)) {
					this.initFilterData();
				}

				if (options.id) {
					useArticleApi({
							ArticleCategoryId: options.id
						})
						.then((res) => {
							if (res && res.Data && Array.isArray(res.Data)) {
								this.bannerList = res.Data;
								this.bannerUrl = res.Data.map((item) => item.CoverImg).filter(
									(img) => img
								);
							}
						})
						.catch((error) => {
							console.error("获取轮播图失败:", error);
							this.bannerList = [];
							this.bannerUrl = [];
						});
				}
			},

			// 添加初始化筛选数据的方法
			// 初始化筛选数据
			initFilterData() {
				try {
					// 获取筛选配置
					this.filterList = Filter[this.merchantsType] || [];
				} catch (error) {
					console.error("初始化筛选数据失败:", error);
					uni.showToast({
						title: this.$t("merchants.filterFailed"),
						icon: "none",
					});
				}
			},

			// 添加处理筛选结果的方法
			// 处理筛选结果
			handleResult(result) {
        this.IsDesc = result;
				if (this.merchantsType === 3) {
					this.searchParams.FiledOrder = `PerConsumption ${result.ShowPrice}`;
				} else if (this.merchantsType === 4) {
					if (Object.keys(result).length > 0) {
						const [type, value] = Object.entries(result)[0];
						this.searchParams[type] = value;
					}
				}
				this.$refs.paging.reload();
			},

			// 查询列表数据
			async queryList(pageNo, pageSize) {
				try {
					// 从store获取选中的位置，添加安全检查
					const selectedLocation = this.$store.state.base?.selectedLocation;

					const params = {
						Index: pageNo,
						Size: pageSize,
						BusinessClassify: this.merchantsType,
						AreaId: selectedLocation?.value || "", // 添加AreaId参数，使用可选链
						...this.searchParams,
					};

					// 请求数据
					const {
						Data
					} = await getShopBgList(params);
					this.$refs.paging.complete(Data || []);
				} catch (error) {
					console.error("获取列表数据失败:", error);
					this.$refs.paging.complete(false);
					uni.showToast({
						title: this.$t("merchants.loadFailed") || "加载失败",
						icon: "none",
					});
				}
			},

			handleCheckScenic(item, isShowDown) {
				if (this.currentCheckId !== item.Id) {
					this.merchantsList.forEach(merchants => {
						this.$refs[`scenicRef_${merchants.Id}`][0].isShowDown = true;
					})
					this.currentCheckId = item.Id;
					this.$refs[`scenicRef_${item.Id}`][0].isShowDown = false;
				} else {
					this.$refs[`scenicRef_${item.Id}`][0].isShowDown = !isShowDown;
				}
			},
			handleCheckStudy(item, isShowDown) {
				if (this.currentCheckId !== item.Id) {
					this.merchantsList.forEach(merchants => {
						this.$refs[`studyRef_${merchants.Id}`][0].isShowDown = true;
					})
					this.currentCheckId = item.Id;
					this.$refs[`studyRef_${item.Id}`][0].isShowDown = false;
				} else {
					this.$refs[`studyRef_${item.Id}`][0].isShowDown = !isShowDown;
				}
			},
			handleCheckPhotography(item, isShowDown) {
				if (this.currentCheckId !== item.Id) {
					this.merchantsList.forEach(merchants => {
						this.$refs[`photographyRef_${merchants.Id}`][0].isShowDown = true;
					})
					this.currentCheckId = item.Id;
					this.$refs[`photographyRef_${item.Id}`][0].isShowDown = false;
				} else {
					this.$refs[`photographyRef_${item.Id}`][0].isShowDown = !isShowDown;
				}
			},

			// 跳转详情
			handleGoToDetail(item) {
				console.log(item);
				uni.navigateTo({
					url: `/mall_subpages/merchants/detail?id=${item.Id}&type=${this.merchantsType}`,
				});
			},

			fabClick(e) {
				// 悬浮按钮点击事件 - 暂时移除购物车相关逻辑
				console.log("悬浮按钮点击", e);
			},
			jumpBanner(index) {
				console.log("dianjile轮播图");
				if (this.bannerList[index].LinkUrl) {
					uni.navigateTo({
						url: this.bannerList[index].LinkUrl
					})
				}
			},
			locationChanged() {
				console.log("emits");
				this.$refs.paging.reload();
			},
			// 搜索功能
			onSearch() {
				// 重新加载数据
				this.$refs.paging.reload();
			},
		},
		watch: {
			// 监听语言变化
			"$i18n.locale": {
				handler(newLocale) {
					// 更新文本
					this.updateContentText();

					// 如果有全部选项，需要更新
					if (this.list1.length > 0 && this.list1[0].name) {
						this.list1[0].name = this.$t("merchants.all");
					}

					// 重新初始化tabs数据
					this.initTabsData();
				},
				immediate: true,
			},
		},
	};
</script>

<style lang="scss" scoped>
	.page-nav-bar {
		/deep/ .left-style {
			background-color: #fff;
		}
	}

	.text {
		margin-top: 50px;
		margin-left: 20px;
		width: 100%;
	}

	/* 新的按钮式选项卡样式 */
	.tabs-container {
		background-color: #fff;
		padding: 20rpx 0;
	}

	.tabs-scroll {
		width: 100%;
		white-space: nowrap;
	}

	.button-tabs {
		padding: 0 20rpx;
		display: inline-flex;
	}

	.tab-button {
		display: inline-block;
		padding: 12rpx 30rpx;
		margin-right: 20rpx;
		background-color: #f5f5f5;
		color: #666;
		font-size: 28rpx;
		border-radius: 50rpx;
		transition: all 0.3s;

		&:last-child {
			margin-right: 0;
		}

		&.tab-button-active {
			background-color: #2979ff;
			color: #fff;
			font-weight: bold;
		}
	}

	.list-search-page {
		position: relative;
		//background-color: #e9e9e9;
		min-height: 100vh;

		/deep/ .select-tab-fixed-top {
			//top: calc(var(--window-top) + 50px);
			z-index: 99999;
		}

		/deep/ .uni-fab {
			z-index: 999998;
		}

		/deep/ .uni-fab__circle {
			z-index: 999999;
		}

		/deep/ .content {
			background: #ffffff;
		}

		/deep/ .popup-layer {
			position: fixed;
		}
	}

	.list-content {
		padding: 30rpx;

		.merchants-list {
			// 移除瀑布流布局样式
		}
	}

	.flex-start {
		/deep/ .select-tab-item {
			justify-content: flex-start !important;
			padding-left: 30rpx;
		}
	}

	/* 搜索框美化 */
	.search-box {
		display: flex;
		align-items: center;
		background: #fff;
		padding: 0 30rpx 0 30rpx;
		// margin: 0 0 20rpx 0;
		height: 80rpx;
		.location {
			display: flex;
			align-items: center;
			border-radius: 100px;
			border: 1px solid #dadbde;
			padding: 6rpx 8rpx;
			opacity: .8;
			&-title {
				font-size: $uni-font-size-base;
			}
			&-arrow {
				width: 0;
				height: 0;
				border-style: solid;
				border-width: 10rpx 6rpx 0 6rpx;
				border-color: #333 transparent transparent transparent;
				margin-left: 10rpx;
			}
		}
		.search {
			flex: 1;
			display: flex;
			align-items: center;
			margin-left: 12rpx;
			input {
				flex: 1;
				border: none;
				outline: none;
				background: transparent;
				font-size: 28rpx;
				color: #333;
				padding: 0 20rpx;
				height: 100%;
				background-color: #eee;
				border-radius: 40rpx;
			}

			.search-btn {
				width: 80rpx;
				margin-left: 8rpx;
				cursor: pointer;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
</style>